package communicationModule;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

/**
 * An object of this class is meant to be run on a separate thread and provides
 * basic multicasting capabilities. After a message has been multicasted the
 * result of the sending operation are stored as a
 * {@link communicationModule.SendResult} object and delivered in a buffered
 * supplied by the {@link communicationModule.Multicast} parent, which is an
 * instance of {@link communicationModule.Multicast}.
 * 
 */
public class BasicMulticast implements Runnable {
    private final MessageObject msg;
    private final ReentrantLock delLock;
    private final Multicast parent;

    public BasicMulticast(final Multicast parent, final ReentrantLock delLock,
            final MessageObject msg) {
        this.parent = parent;
        this.msg = msg;
        this.delLock = delLock;
    }

    @Override
    public void run() {

        final ArrayList<String> badrcv = new ArrayList<String>();

        for (final String rescvr : msg.getGroupView().getView().keySet()) {
            try {
                msg.getGroupView().getView().get(rescvr).send(msg);
            } catch (final RemoteException e) {
                badrcv.add(rescvr);
            }
        }

        delLock.lock();
        parent.getDeliverbuffer().add(new SendResult(msg, badrcv));
        delLock.unlock();
    }
}
